/**
 * 浏览器工作流 - 内容脚本
 * 实现事件监听、录制和回放功能
 */

// 避免重复注入
if (typeof window.browserWorkInjected === "undefined") {
  window.browserWorkInjected = true;

  console.log("浏览器工作流内容脚本已加载");

  // 状态变量
  let isRecording = false;
  let recordedActions = [];
  let recordingStartTime = 0; // 录制开始时间
  let playbackMode = false;
  let currentPlaybackIndex = 0;
  let playbackActions = [];
  let floatingButton = null;
  let logWindow = null;
  let scrollObserver = null;
  let highlightTimers = new Map(); // 管理高亮定时器
  let currentHighlightedElements = new Set(); // 当前高亮的元素
  let settings = {
    showLogs: false,
    highlightElements: true,
    highlightColor: "#ff6b6b",
    showFloatingButton: false,
    playbackSpeed: 500,
    useOriginalTimings: true,
    debugMode: false,
  };

  /**
   * 获取元素的稳定属性
   * @param {Element} element - DOM元素
   * @returns {Object} 稳定属性对象
   */
  function getStableAttributes(element) {
    const stableAttrs = {};

    // 优先级1: 测试专用属性
    if (element.dataset.testid) stableAttrs["data-testid"] = element.dataset.testid;
    if (element.dataset.qa) stableAttrs["data-qa"] = element.dataset.qa;
    if (element.dataset.cy) stableAttrs["data-cy"] = element.dataset.cy;

    // 优先级2: 表单相关属性
    if (element.name) stableAttrs.name = element.name;
    if (element.type && ["button", "submit", "input", "select", "textarea"].includes(element.tagName.toLowerCase())) {
      stableAttrs.type = element.type;
    }

    // 优先级3: 无障碍属性
    if (element.getAttribute("aria-label")) stableAttrs["aria-label"] = element.getAttribute("aria-label");
    if (element.getAttribute("aria-labelledby")) stableAttrs["aria-labelledby"] = element.getAttribute("aria-labelledby");
    if (element.getAttribute("role")) stableAttrs.role = element.getAttribute("role");

    // 优先级4: 其他有用属性
    if (element.placeholder) stableAttrs.placeholder = element.placeholder;
    if (element.title) stableAttrs.title = element.title;
    if (element.alt) stableAttrs.alt = element.alt;
    if (element.href && element.tagName === "A") stableAttrs.href = element.href;

    return stableAttrs;
  }

  /**
   * 生成绝对路径选择器（从body开始的完整路径）
   * @param {Element} element - DOM元素
   * @returns {Object} 选择器对象
   */
  function generateElementSelectors(element) {
    if (!element) {
      return {
        primary: "",
        absolutePath: "",
        elementInfo: {},
      };
    }

    try {
      const absolutePath = generateAbsolutePath(element);

      return {
        primary: absolutePath,
        absolutePath: absolutePath,
        elementInfo: {
          tagName: element.tagName.toLowerCase(),
          text: element.textContent?.trim().slice(0, 100) || "",
          className: element.className || "",
          id: element.id || "",
          name: element.name || "",
          type: element.type || "",
          placeholder: element.placeholder || "",
        },
      };
    } catch (error) {
      console.error("生成绝对路径失败:", error);
      return {
        primary: "body",
        absolutePath: "body",
        elementInfo: { tagName: element.tagName?.toLowerCase() || "unknown" },
      };
    }
  }

  /**
   * 生成从body开始的绝对DOM路径
   * @param {Element} element - 目标元素
   * @returns {string} 绝对路径选择器
   */
  function generateAbsolutePath(element) {
    if (!element || element === document.body) {
      return "body";
    }

    const path = [];
    let current = element;

    while (current && current !== document.body) {
      let selector = current.tagName.toLowerCase();

      if (current.parentElement) {
        const siblings = Array.from(current.parentElement.children);
        const index = siblings.indexOf(current) + 1;
        selector += `:nth-child(${index})`;
      }

      path.unshift(selector);
      current = current.parentElement;
    }

    return "body > " + path.join(" > ");
  }

  /**
   * 通过绝对路径查找元素
   * @param {Object} selectors - 选择器对象
   * @returns {Element|null} DOM元素
   */
  function findElementBySelectors(selectors) {
    if (!selectors?.absolutePath) {
      return null;
    }

    try {
      return document.querySelector(selectors.absolutePath);
    } catch (error) {
      console.error("绝对路径查找失败:", error);
      return null;
    }
  }

  /**
   * 根据文本内容查找元素
   * @param {string} text - 文本内容
   * @param {string} tagName - 标签名
   * @param {boolean} fuzzy - 是否模糊匹配
   * @returns {Element|null} DOM元素
   */
  function findElementByText(text, tagName, fuzzy = false) {
    if (!text) return null;

    try {
      const elements = document.querySelectorAll(tagName);
      for (const element of elements) {
        const elementText = element.textContent?.trim() || "";

        if (fuzzy) {
          if (elementText.includes(text) || text.includes(elementText)) {
            return element;
          }
        } else {
          if (elementText === text) {
            return element;
          }
        }

        if (element.getAttribute("aria-label") === text || element.getAttribute("title") === text) {
          return element;
        }
      }
      return null;
    } catch (error) {
      console.error("文本查找失败:", error);
      return null;
    }
  }

  /**
   * 通过选择器查找元素（兼容旧接口）
   * @param {string|Object} selector - CSS选择器或选择器对象
   * @returns {Element|null} DOM元素
   */
  function findElementBySelector(selector) {
    if (typeof selector === "string") {
      try {
        return document.querySelector(selector);
      } catch (error) {
        console.warn("无效的选择器:", selector, error);
        return null;
      }
    } else if (typeof selector === "object") {
      return findElementBySelectors(selector);
    }
    return null;
  }

  /**
   * 记录操作
   * @param {string} type - 操作类型
   * @param {Element} element - 目标元素
   * @param {Object} data - 额外数据
   */
  function recordAction(type, element, data = {}) {
    if (!isRecording) return;

    try {
      const selectorInfo = generateElementSelectors(element);
      const currentTime = Date.now();

      const action = {
        type: type,
        timestamp: currentTime,
        relativeTime: recordingStartTime > 0 ? currentTime - recordingStartTime : 0, // 相对录制开始的时间
        selector: selectorInfo.primary,
        selectors: selectorInfo,
        elementInfo: {
          tagName: element.tagName.toLowerCase(),
          text: element.textContent ? element.textContent.slice(0, 100) : "",
          value: element.value || "",
          href: element.href || "",
          className: element.className || "",
          stableAttributes: getStableAttributes(element),
        },
        data: data,
        url: window.location.href,
        scrollPosition: {
          x: window.pageXOffset,
          y: window.pageYOffset,
        },
      };

      recordedActions.push(action);

      // 调试信息
      if (settings.debugMode) {
        const prevAction = recordedActions[recordedActions.length - 2];
        const interval = prevAction ? currentTime - prevAction.timestamp : 0;
        console.log(`📝 录制操作 [${recordedActions.length}]: ${type} (间隔: ${interval}ms, 总时长: ${action.relativeTime}ms)`);
      }

      // 高亮元素
      if (settings.highlightElements) {
        highlightElement(element);
      }

      // 显示日志
      if (settings.showLogs) {
        showActionLog(action);
      }

      // 保存到存储
      chrome.storage.local.set({
        recordedActions: recordedActions,
        isRecording: isRecording,
      });

      // 通知popup更新
      chrome.runtime.sendMessage({ type: "ACTION_RECORDED", action: action }).catch(() => {
        // 忽略错误，popup可能未打开
      });
    } catch (error) {
      console.error("记录操作失败:", error);
    }
  }



  /**
   * 清除元素的高亮效果
   * @param {Element} element - 要清除高亮的元素
   */
  function clearElementHighlight(element) {
    if (!element) return;

    try {
      // 停止该元素的闪烁定时器
      if (highlightTimers.has(element)) {
        clearInterval(highlightTimers.get(element));
        highlightTimers.delete(element);
      }

      // 移除高亮标记
      currentHighlightedElements.delete(element);
      
      // 添加清理状态类
      element.classList.add("browser-work-highlight-clearing");
      
      // 清除高亮样式
      element.classList.remove("browser-work-highlight");
      
      // 恢复原始样式
      if (element.hasAttribute('data-original-outline')) {
        element.style.outline = element.getAttribute('data-original-outline');
        element.removeAttribute('data-original-outline');
      } else {
        element.style.outline = '';
      }
      
      // 延迟移除清理状态类，确保样式生效
      setTimeout(() => {
        try {
          element.classList.remove("browser-work-highlight-clearing");
        } catch (e) {
          // 元素可能已被移除，忽略错误
        }
      }, 50);
      
      if (settings.debugMode) {
        console.log("✨ 清除元素高亮:", element.tagName);
      }
    } catch (error) {
      console.error("清除元素高亮失败:", error);
    }
  }

  /**
   * 清除所有高亮效果
   */
  function clearAllHighlights() {
    try {
      // 清除所有定时器
      highlightTimers.forEach((timer, element) => {
        clearInterval(timer);
        clearElementHighlight(element);
      });
      
      highlightTimers.clear();
      currentHighlightedElements.clear();
      
      // 额外保险：清除页面上所有可能残留的高亮类
      document.querySelectorAll('.browser-work-highlight').forEach(element => {
        clearElementHighlight(element);
      });
      
      if (settings.debugMode) {
        console.log("🧹 已清除所有高亮效果");
      }
    } catch (error) {
      console.error("清除所有高亮失败:", error);
    }
  }

  /**
   * 高亮元素（改进版）
   * @param {Element} element - 要高亮的元素
   */
  function highlightElement(element) {
    if (!element || !settings.highlightElements) return;

    try {
      // 检查元素是否仍在DOM中
      if (!document.contains(element)) {
        console.warn("⚠️ 尝试高亮已移除的元素");
        return;
      }

      // 如果元素已经在高亮中，先清除之前的高亮
      if (currentHighlightedElements.has(element)) {
        clearElementHighlight(element);
      }

      // 保存原始样式
      element.setAttribute('data-original-outline', element.style.outline || '');

      const highlightColor = settings.highlightColor || "#ff6b6b";

      // 添加高亮标记
      element.classList.add("browser-work-highlight");
      currentHighlightedElements.add(element);

      let blinkCount = 0;
      const maxBlinks = 6; // 闪烁3次（每次包含显示和隐藏）
      
      const blinkInterval = setInterval(() => {
        try {
          // 再次检查元素是否还在DOM中
          if (!document.contains(element)) {
            clearElementHighlight(element);
            return;
          }

          if (blinkCount % 2 === 0) {
            // 显示高亮
            element.style.outline = `2px solid ${highlightColor}`;
          } else {
            // 隐藏高亮
            element.style.outline = element.getAttribute('data-original-outline') || '';
          }

          blinkCount++;
          
          // 完成闪烁后清理
          if (blinkCount >= maxBlinks) {
            clearElementHighlight(element);
          }
        } catch (error) {
          console.error("闪烁过程中出错:", error);
          clearElementHighlight(element);
        }
      }, 250); // 减少闪烁间隔，提升响应感

      // 保存定时器引用
      highlightTimers.set(element, blinkInterval);

      // 安全保险：最多3秒后强制清理
      setTimeout(() => {
        if (currentHighlightedElements.has(element)) {
          clearElementHighlight(element);
          console.warn("⚠️ 强制清理超时的高亮效果");
        }
      }, 3000);

      if (settings.debugMode) {
        console.log("✨ 开始高亮元素:", element.tagName, "颜色:", highlightColor);
      }
      
    } catch (error) {
      console.error("高亮元素失败:", error);
      // 发生错误时尝试清理
      clearElementHighlight(element);
    }
  }

  /**
   * 显示操作日志
   * @param {Object} action - 操作数据
   */
  function showActionLog(action) {
    try {
      if (!settings.showLogs) {
        if (logWindow && !logWindow.closed) {
          logWindow.close();
          logWindow = null;
        }
        return;
      }

      if (!logWindow || logWindow.closed) {
        createLogWindow();
      }

      if (logWindow && !logWindow.closed) {
        const logDoc = logWindow.document;
        const logEntry = logDoc.createElement("div");
        logEntry.className = "log-entry";
        logEntry.innerHTML = `
          <div class="log-header">
            <span class="log-type">${action.type}</span>
            <span class="log-time">${new Date(action.timestamp).toLocaleTimeString()}</span>
          </div>
          <div class="log-details">
            <div><strong>元素:</strong> ${action.elementInfo.tagName}</div>
            <div><strong>选择器:</strong> ${action.selector}</div>
            ${action.elementInfo.text ? `<div><strong>文本:</strong> ${action.elementInfo.text}</div>` : ""}
            ${action.data && Object.keys(action.data).length > 0 ? `<div><strong>数据:</strong> ${JSON.stringify(action.data)}</div>` : ""}
          </div>
        `;

        const logContainer = logDoc.getElementById("log-container");
        if (logContainer) {
          logContainer.appendChild(logEntry);
          logContainer.scrollTop = logContainer.scrollHeight;
        }
      }
    } catch (error) {
      console.error("显示日志失败:", error);
    }
  }

  /**
   * 创建日志窗口
   */
  function createLogWindow() {
    try {
      const logWindowFeatures = "width=400,height=600,resizable=yes,scrollbars=yes";
      logWindow = window.open("", "browser-work-logs", logWindowFeatures);

      if (logWindow) {
        logWindow.document.write(`
          <!DOCTYPE html>
          <html>
          <head>
            <title>浏览器工作流 - 操作日志</title>
            <style>
              body { 
                font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; 
                margin: 0; padding: 10px; background: #f8f9fa; 
              }
              .header { 
                background: #667eea; color: white; padding: 10px; 
                border-radius: 5px; margin-bottom: 10px; text-align: center; 
              }
              #log-container { 
                max-height: 500px; overflow-y: auto; 
              }
              .log-entry { 
                background: white; margin-bottom: 8px; padding: 10px; 
                border-radius: 5px; border-left: 4px solid #667eea; 
              }
              .log-header { 
                display: flex; justify-content: space-between; 
                margin-bottom: 5px; font-weight: bold; 
              }
              .log-type { 
                background: #e9ecef; padding: 2px 6px; 
                border-radius: 3px; font-size: 12px; 
              }
              .log-time { 
                color: #6c757d; font-size: 12px; 
              }
              .log-details { 
                font-size: 13px; color: #495057; 
              }
              .log-details div { 
                margin-bottom: 3px; 
              }
              .clear-btn { 
                background: #dc3545; color: white; border: none; 
                padding: 5px 10px; border-radius: 3px; cursor: pointer; 
              }
            </style>
          </head>
          <body>
            <div class="header">
              <h3>浏览器工作流 - 操作日志</h3>
              <button class="clear-btn" onclick="document.getElementById('log-container').innerHTML=''">清空日志</button>
            </div>
            <div id="log-container"></div>
          </body>
          </html>
        `);
        logWindow.document.close();
      }
    } catch (error) {
      console.error("创建日志窗口失败:", error);
    }
  }

  /**
   * 创建拖拽功能
   * @param {Element} element - 要添加拖拽的元素
   */
  function makeDraggable(element) {
    let isDragging = false;
    let startX, startY, startLeft, startTop;

    element.addEventListener("mousedown", function (e) {
      if (e.target.classList.contains("drag-handle") || element.classList.contains("draggable")) {
        isDragging = true;
        startX = e.clientX;
        startY = e.clientY;
        startLeft = parseInt(window.getComputedStyle(element).left, 10) || 0;
        startTop = parseInt(window.getComputedStyle(element).top, 10) || 0;

        e.preventDefault();
        element.style.zIndex = "10001";
      }
    });

    document.addEventListener("mousemove", function (e) {
      if (isDragging) {
        const deltaX = e.clientX - startX;
        const deltaY = e.clientY - startY;
        element.style.left = startLeft + deltaX + "px";
        element.style.top = startTop + deltaY + "px";
      }
    });

    document.addEventListener("mouseup", function () {
      if (isDragging) {
        isDragging = false;
        element.style.zIndex = "10000";
      }
    });
  }

  /**
   * 创建浮动按钮
   */
  function createFloatingButton() {
    if (floatingButton) return;

    try {
      floatingButton = document.createElement("div");
      floatingButton.className = "browser-work-floating-btn draggable";
      floatingButton.innerHTML = `
        <div class="floating-btn-content">
          <span class="btn-icon">${isRecording ? "⏹" : "⏺"}</span>
        </div>
      `;

      Object.assign(floatingButton.style, {
        position: "fixed",
        bottom: "20px",
        right: "20px",
        width: "60px",
        height: "60px",
        borderRadius: "50%",
        background: isRecording ? "linear-gradient(135deg, #dc3545 0%, #fd7e14 100%)" : "linear-gradient(135deg, #28a745 0%, #20c997 100%)",
        color: "white",
        border: "none",
        boxShadow: "0 4px 20px rgba(0,0,0,0.3)",
        cursor: "pointer",
        zIndex: "10000",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        fontSize: "24px",
        transition: "all 0.3s ease",
        userSelect: "none",
      });

      floatingButton.addEventListener("click", function () {
        chrome.runtime
          .sendMessage({
            type: isRecording ? "STOP_RECORDING_FROM_FLOAT" : "START_RECORDING_FROM_FLOAT",
          })
          .catch(() => {
            console.error("发送浮动按钮消息失败");
          });
      });

      floatingButton.addEventListener("mouseenter", function () {
        this.style.transform = "scale(1.1)";
      });

      floatingButton.addEventListener("mouseleave", function () {
        this.style.transform = "scale(1)";
      });

      makeDraggable(floatingButton);
      document.body.appendChild(floatingButton);
    } catch (error) {
      console.error("创建浮动按钮失败:", error);
    }
  }

  /**
   * 更新浮动按钮状态
   */
  function updateFloatingButton() {
    if (!floatingButton) return;

    try {
      const icon = floatingButton.querySelector(".btn-icon");
      if (isRecording) {
        icon.textContent = "⏹";
        floatingButton.style.background = "linear-gradient(135deg, #dc3545 0%, #fd7e14 100%)";
      } else {
        icon.textContent = "⏺";
        floatingButton.style.background = "linear-gradient(135deg, #28a745 0%, #20c997 100%)";
      }
    } catch (error) {
      console.error("更新浮动按钮失败:", error);
    }
  }

  /**
   * 移除浮动按钮
   */
  function removeFloatingButton() {
    try {
      if (floatingButton?.parentNode) {
        floatingButton.parentNode.removeChild(floatingButton);
        floatingButton = null;
      }
    } catch (error) {
      console.error("移除浮动按钮失败:", error);
    }
  }

  // 事件监听器

  /**
   * 点击事件监听
   */
  function handleClick(event) {
    if (!isRecording) return;

    const target = event.target;

    // 忽略浏览器工作流自己的元素
    if (target.closest(".browser-work-floating-btn") || target.classList.contains("browser-work-notification") || target.closest(".browser-work-toolbar")) {
      return;
    }

    recordAction("click", target, {
      clientX: event.clientX,
      clientY: event.clientY,
      button: event.button,
      ctrlKey: event.ctrlKey,
      shiftKey: event.shiftKey,
      altKey: event.altKey,
    });
  }

  /**
   * 输入事件监听
   */
  function handleInput(event) {
    if (!isRecording) return;

    recordAction("input", event.target, {
      value: event.target.value,
      inputType: event.inputType || "input",
    });
  }

  /**
   * 键盘事件监听
   */
  function handleKeydown(event) {
    if (!isRecording) return;

    // 只记录特殊键
    if (["Enter", "Tab", "Escape"].includes(event.key)) {
      recordAction("keydown", event.target, {
        key: event.key,
        code: event.code,
        ctrlKey: event.ctrlKey,
        shiftKey: event.shiftKey,
        altKey: event.altKey,
      });
    }
  }

  /**
   * 滚动事件监听
   */
  const handleScroll = function (event) {
    if (!isRecording) return;

    const target = event.target;
    let scrollElement, scrollData;

    if (target === document || target === document.documentElement || target === window) {
      scrollElement = document.documentElement;
      scrollData = {
        type: "window",
        scrollX: window.pageXOffset,
        scrollY: window.pageYOffset,
        scrollWidth: document.documentElement.scrollWidth,
        scrollHeight: document.documentElement.scrollHeight,
      };
    } else {
      scrollElement = target;
      scrollData = {
        type: "element",
        scrollLeft: target.scrollLeft,
        scrollTop: target.scrollTop,
        scrollWidth: target.scrollWidth,
        scrollHeight: target.scrollHeight,
        clientWidth: target.clientWidth,
        clientHeight: target.clientHeight,
      };
    }

    recordAction("scroll", scrollElement, scrollData);
  };

  // 节流函数
  const scrollTimeouts = new WeakMap();
  const throttledScroll = function (event) {
    const target = event.target === document ? window : event.target;

    if (scrollTimeouts.has(target)) return;

    const timeout = setTimeout(() => {
      handleScroll(event);
      scrollTimeouts.delete(target);
    }, 200);

    scrollTimeouts.set(target, timeout);
  };

  /**
   * 为页面中所有可滚动元素添加滚动监听
   */
  function addScrollListeners() {
    window.addEventListener("scroll", throttledScroll, true);
    document.addEventListener("scroll", throttledScroll, true);

    addScrollListenersToElements();

    const observer = new MutationObserver(function (mutations) {
      mutations.forEach(function (mutation) {
        mutation.addedNodes.forEach(function (node) {
          if (node.nodeType === Node.ELEMENT_NODE) {
            addScrollListenersToElement(node);
            const scrollableChildren = node.querySelectorAll ? node.querySelectorAll("*") : [];
            scrollableChildren.forEach(addScrollListenersToElement);
          }
        });
      });
    });

    observer.observe(document.body, {
      childList: true,
      subtree: true,
    });

    return observer;
  }

  /**
   * 为所有现有的可滚动元素添加监听
   */
  function addScrollListenersToElements() {
    document.querySelectorAll("*").forEach(addScrollListenersToElement);
  }

  /**
   * 为单个元素添加滚动监听
   */
  function addScrollListenersToElement(element) {
    if (isScrollableElement(element) && !element.hasScrollListener) {
      element.addEventListener("scroll", throttledScroll, true);
      element.hasScrollListener = true;
    }
  }

  /**
   * 判断元素是否可滚动
   */
  function isScrollableElement(element) {
    if (!element || element.nodeType !== Node.ELEMENT_NODE) return false;

    const style = window.getComputedStyle(element);
    const overflowX = style.overflowX;
    const overflowY = style.overflowY;

    const hasScrollStyle = ["auto", "scroll"].includes(overflowX) || ["auto", "scroll"].includes(overflowY);

    const canScrollHorizontally = element.scrollWidth > element.clientWidth;
    const canScrollVertically = element.scrollHeight > element.clientHeight;

    return hasScrollStyle && (canScrollHorizontally || canScrollVertically);
  }

  /**
   * 移除所有滚动事件监听
   */
  function removeScrollListeners() {
    window.removeEventListener("scroll", throttledScroll, true);
    document.removeEventListener("scroll", throttledScroll, true);

    document.querySelectorAll("*").forEach(function (element) {
      if (element.hasScrollListener) {
        element.removeEventListener("scroll", throttledScroll, true);
        element.hasScrollListener = false;
      }
    });

    if (scrollObserver) {
      scrollObserver.disconnect();
      scrollObserver = null;
    }
  }

  /**
   * 开始录制
   */
  async function startRecording() {
    if (isRecording) {
      return { success: true, message: "已经在录制中" };
    }

    try {
      await loadSettings();

      isRecording = true;
      recordedActions = [];
      recordingStartTime = Date.now(); // 记录开始时间

      document.addEventListener("click", handleClick, true);
      document.addEventListener("input", handleInput, true);
      document.addEventListener("keydown", handleKeydown, true);

      scrollObserver = addScrollListeners();
      updateFloatingButton();

      chrome.storage.local.set({ 
        isRecording: true, 
        recordedActions: [],
        recordingStartTime: recordingStartTime
      });

      console.log("🎬 开始录制用户操作，设置已加载:", settings);
      console.log("📅 录制开始时间:", new Date(recordingStartTime).toLocaleString());
      return { success: true, message: "录制已开始" };
    } catch (error) {
      console.error("开始录制失败:", error);
      return { success: false, error: error.message };
    }
  }

  /**
   * 停止录制
   */
  function stopRecording() {
    if (!isRecording) {
      return { success: true, actions: [], message: "当前未在录制" };
    }

    try {
      isRecording = false;
      const recordingEndTime = Date.now();
      const totalDuration = recordingEndTime - recordingStartTime;

      document.removeEventListener("click", handleClick, true);
      document.removeEventListener("input", handleInput, true);
      document.removeEventListener("keydown", handleKeydown, true);

      removeScrollListeners();
      updateFloatingButton();
      
      // 清除所有高亮效果
      clearAllHighlights();

      chrome.storage.local.set({
        isRecording: false,
        recordedActions: recordedActions,
      });

      console.log("⏹️ 停止录制，共记录", recordedActions.length, "个操作");
      console.log("⏱️ 录制总时长:", Math.round(totalDuration / 1000 * 100) / 100, "秒");
      
      // 计算平均操作间隔
      if (recordedActions.length > 1) {
        const avgInterval = totalDuration / (recordedActions.length - 1);
        console.log("📊 平均操作间隔:", Math.round(avgInterval), "ms");
      }
      
      return { success: true, actions: recordedActions, duration: totalDuration };
    } catch (error) {
      console.error("停止录制失败:", error);
      return { success: false, error: error.message };
    }
  }

  /**
   * 执行单个操作
   * @param {Object} action - 操作数据
   * @param {number} stepIndex - 步骤索引
   */
  async function executeAction(action, stepIndex = 0) {
    let element = null;
    const stepNumber = stepIndex + 1;

    // 智能元素查找策略
    if (action.selectors) {
      element = findElementBySelectors(action.selectors);
    } else {
      element = findElementBySelector(action.selector);
    }

    if (!element && action.elementInfo?.text) {
      element = findElementByText(action.elementInfo.text, action.elementInfo.tagName, true);
    }

    if (!element) {
      const elementDescription = action.elementInfo ? `"${action.elementInfo.text || action.elementInfo.tagName}"` : "未知元素";
      const selectorInfo = action.selectors ? `主选择器: ${action.selectors.primary}` : `选择器: ${action.selector}`;

      const errorMsg = `回放失败！第${stepNumber}步操作无法执行，未找到目标元素 ${elementDescription}\n选择器信息: ${selectorInfo}\n操作类型: ${action.type}`;
      console.error(errorMsg);
      throw new Error(errorMsg);
    }

    // 滚动到元素位置
    element.scrollIntoView({ behavior: "smooth", block: "center" });
    await new Promise((resolve) => setTimeout(resolve, 300));

    // 高亮元素
    if (settings.highlightElements) {
      highlightElement(element);
    }

    // 执行操作
    switch (action.type) {
      case "click":
        element.click();
        break;

      case "input":
        if (["INPUT", "TEXTAREA"].includes(element.tagName)) {
          element.focus();
          element.value = action.data.value || "";
          element.dispatchEvent(new Event("input", { bubbles: true }));
          element.dispatchEvent(new Event("change", { bubbles: true }));
        }
        break;

      case "keydown":
        element.focus();
        const keyEvent = new KeyboardEvent("keydown", {
          key: action.data.key,
          code: action.data.code,
          ctrlKey: action.data.ctrlKey,
          shiftKey: action.data.shiftKey,
          altKey: action.data.altKey,
          bubbles: true,
        });
        element.dispatchEvent(keyEvent);
        break;

      case "scroll":
        if (action.data.type === "window") {
          window.scrollTo({
            left: action.data.scrollX,
            top: action.data.scrollY,
            behavior: "smooth",
          });
        } else if (action.data.type === "element") {
          if (element) {
            element.scrollTo({
              left: action.data.scrollLeft,
              top: action.data.scrollTop,
              behavior: "smooth",
            });
          }
        } else {
          window.scrollTo({
            left: action.data.scrollX || 0,
            top: action.data.scrollY || 0,
            behavior: "smooth",
          });
        }
        break;

      default:
        console.warn("未知的操作类型:", action.type);
    }

    // 显示日志
    if (settings.showLogs) {
      showActionLog({ ...action, type: "REPLAY_" + action.type });
    }
  }

  /**
   * 计算智能等待时间
   * @param {Object} currentAction - 当前操作
   * @param {Object} nextAction - 下一个操作
   * @returns {number} 等待时间（毫秒）
   */
  function calculateWaitTime(currentAction, nextAction) {
    if (!settings.useOriginalTimings) {
      return settings.playbackSpeed;
    }

    if (!currentAction.timestamp || !nextAction.timestamp) {
      console.warn("⚠️ 操作缺少时间戳，使用固定间隔");
      return settings.playbackSpeed;
    }

    const originalInterval = nextAction.timestamp - currentAction.timestamp;
    
    // 智能时间间隔处理
    let adjustedInterval = originalInterval;
    
    // 处理异常长的间隔（可能是用户暂停了）
    if (originalInterval > 10000) { // 超过10秒
      adjustedInterval = Math.min(originalInterval, 3000); // 限制为最多3秒
      console.log(`⏰ 检测到长间隔 ${originalInterval}ms，调整为 ${adjustedInterval}ms`);
    }
    
    // 处理过短的间隔
    if (originalInterval < 50) {
      adjustedInterval = 100; // 最少100ms，给页面响应时间
      console.log(`⏰ 检测到短间隔 ${originalInterval}ms，调整为 ${adjustedInterval}ms`);
    }
    
    // 最终安全范围限制
    const finalWaitTime = Math.min(Math.max(adjustedInterval, 50), 5000);
    
    if (settings.debugMode) {
      console.log(`⏱️ 时间计算: 原始=${originalInterval}ms, 调整=${adjustedInterval}ms, 最终=${finalWaitTime}ms`);
    }
    
    return finalWaitTime;
  }

  /**
   * 开始回放
   * @param {Array} actions - 操作列表
   */
  async function startPlayback(actions) {
    if (playbackMode) {
      return { success: false, error: "已经在回放中" };
    }

    try {
      await loadSettings();

      playbackMode = true;
      playbackActions = actions;
      currentPlaybackIndex = 0;

      const timingMode = settings.useOriginalTimings ? "原始时间间隔" : `固定间隔 ${settings.playbackSpeed}ms`;
      console.log(`🎬 开始回放 ${actions.length} 个操作，使用 ${timingMode}`);
      
      if (settings.useOriginalTimings && actions.length > 1) {
        const totalOriginalTime = actions[actions.length - 1].timestamp - actions[0].timestamp;
        console.log(`📊 原始录制时长: ${Math.round(totalOriginalTime / 1000 * 100) / 100}秒`);
      }

      const playbackStartTime = Date.now();

      for (let i = 0; i < playbackActions.length; i++) {
        if (!playbackMode) break;

        currentPlaybackIndex = i;
        const action = playbackActions[i];

        try {
          console.log(`▶️ 执行第 ${i + 1}/${playbackActions.length} 步: ${action.type}`);
          await executeAction(action, i);
        } catch (error) {
          throw error;
        }

        // 计算等待时间
        if (i < playbackActions.length - 1) {
          const nextAction = playbackActions[i + 1];
          const waitTime = calculateWaitTime(action, nextAction);
          
          if (settings.useOriginalTimings) {
            console.log(`⏸️ 等待 ${waitTime}ms (原始间隔模式)`);
          }
          
          await new Promise((resolve) => setTimeout(resolve, waitTime));
        }
      }

      playbackMode = false;
      const playbackDuration = Date.now() - playbackStartTime;
      
      // 清除所有高亮效果
      clearAllHighlights();
      
      console.log("✅ 回放完成！");
      console.log(`⏱️ 实际回放时长: ${Math.round(playbackDuration / 1000 * 100) / 100}秒`);
      
      chrome.runtime.sendMessage({ 
        type: "PLAYBACK_COMPLETE",
        data: {
          duration: playbackDuration,
          actionCount: playbackActions.length,
          timingMode: settings.useOriginalTimings ? "original" : "fixed"
        }
      }).catch(() => {
        console.log("无法发送回放完成消息");
      });

      return { success: true, duration: playbackDuration };
    } catch (error) {
      playbackMode = false;
      
      // 清除所有高亮效果
      clearAllHighlights();
      
      const errorMessage = `回放在第 ${currentPlaybackIndex + 1} 步失败: ${error.message}`;

      chrome.runtime
        .sendMessage({
          type: "PLAYBACK_ERROR",
          error: errorMessage,
        })
        .catch(() => {
          console.log("无法发送回放错误消息");
        });

      console.error("❌ 回放失败:", errorMessage);
      return { success: false, error: errorMessage };
    }
  }

  /**
   * 停止回放
   */
  function stopPlayback() {
    playbackMode = false;
    currentPlaybackIndex = 0;
    playbackActions = [];
    
    // 清除所有高亮效果
    clearAllHighlights();
    
    return { success: true };
  }

  /**
   * 加载设置
   */
  async function loadSettings() {
    try {
      const result = await chrome.storage.sync.get([
        "showLogs", "highlightElements", "highlightColor", 
        "showFloatingButton", "playbackSpeed", "useOriginalTimings", "debugMode"
      ]);

      settings = {
        showLogs: result.showLogs !== undefined ? result.showLogs : false,
        highlightElements: result.highlightElements !== false,
        highlightColor: result.highlightColor || "#ff6b6b",
        showFloatingButton: result.showFloatingButton || false,
        playbackSpeed: result.playbackSpeed || 500,
        useOriginalTimings: result.useOriginalTimings !== undefined ? result.useOriginalTimings : true,
        debugMode: result.debugMode || false,
      };

      if (settings.showFloatingButton) {
        createFloatingButton();
      } else {
        removeFloatingButton();
      }
    } catch (error) {
      console.error("加载设置失败:", error);
    }
  }

  /**
   * 监听来自popup和background的消息
   */
  chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
    try {
      switch (request.type) {
        case "PING":
          sendResponse({ success: true, message: "Content script is ready" });
          break;

        case "GET_RECORDING_STATUS":
          sendResponse({
            success: true,
            isRecording: isRecording,
            actionsCount: recordedActions.length,
          });
          break;

        case "START_RECORDING":
          startRecording().then((startResult) => {
            sendResponse(startResult);
          });
          return true;

        case "STOP_RECORDING":
          sendResponse(stopRecording());
          break;

        case "START_PLAYBACK":
          startPlayback(request.data.actions).then((result) => {
            sendResponse(result);
          });
          return true;

        case "STOP_PLAYBACK":
          sendResponse(stopPlayback());
          break;

        case "UPDATE_SETTINGS":
          loadSettings().then(() => {
            sendResponse({ success: true });
          });
          return true;

        case "GET_PAGE_INFO":
          sendResponse({
            success: true,
            data: {
              title: document.title,
              url: window.location.href,
              domain: window.location.hostname,
            },
          });
          break;

        case "CONTINUE_RECORDING":
          if (isRecording) {
            sendResponse({ success: true, message: "继续录制" });
          } else {
            sendResponse({ success: false, message: "当前未在录制" });
          }
          break;

        default:
          console.warn("内容脚本收到未知消息类型:", request.type);
          sendResponse({ success: false, error: "未知的消息类型" });
      }
    } catch (error) {
      console.error("处理消息失败:", error);
      sendResponse({ success: false, error: error.message });
    }

    return true;
  });

  /**
   * 页面加载完成后的初始化
   */
  async function initialize() {
    try {
      await loadSettings();

      chrome.storage.local.get(["isRecording", "recordedActions"], function (result) {
        if (result.isRecording) {
          console.log("检测到正在进行的录制，继续录制");
          isRecording = true;
          recordedActions = result.recordedActions || [];
          recordingStartTime = result.recordingStartTime || Date.now(); // 恢复录制开始时间

          document.addEventListener("click", handleClick, true);
          document.addEventListener("input", handleInput, true);
          document.addEventListener("keydown", handleKeydown, true);

          if (!scrollObserver) {
            scrollObserver = addScrollListeners();
          }
          updateFloatingButton();
        }
      });

      chrome.runtime
        .sendMessage({
          type: "PAGE_LOADED",
          data: {
            url: window.location.href,
            title: document.title,
          },
        })
        .catch(() => {
          console.log("无法发送页面加载消息");
        });
    } catch (error) {
      console.error("初始化失败:", error);
    }
  }

  // 监听设置变化
  chrome.storage.onChanged.addListener(function (changes, areaName) {
    if (areaName === "sync") {
      const oldShowLogs = settings.showLogs;
      const oldHighlightElements = settings.highlightElements;
      
      loadSettings().then(() => {
        if (oldShowLogs && !settings.showLogs) {
          if (logWindow && !logWindow.closed) {
            logWindow.close();
            logWindow = null;
          }
        }
        
        // 如果禁用了元素高亮功能，清除所有现有高亮
        if (oldHighlightElements && !settings.highlightElements) {
          clearAllHighlights();
          console.log("🧹 禁用高亮功能，清除所有高亮效果");
        }
      });
    }
  });

  // 页面卸载时清理高亮效果
  window.addEventListener('beforeunload', function() {
    try {
      clearAllHighlights();
      console.log("🧹 页面卸载时清理高亮效果");
    } catch (error) {
      console.error("页面卸载清理失败:", error);
    }
  });

  // 监听页面隐藏事件（如切换标签页）
  document.addEventListener('visibilitychange', function() {
    if (document.hidden) {
      try {
        clearAllHighlights();
        console.log("🧹 页面隐藏时清理高亮效果");
      } catch (error) {
        console.error("页面隐藏清理失败:", error);
      }
    }
  });

  // DOM变化监听，清理已移除元素的高亮
  const domObserver = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutation) {
      if (mutation.type === 'childList' && mutation.removedNodes.length > 0) {
        mutation.removedNodes.forEach(function(node) {
          if (node.nodeType === Node.ELEMENT_NODE) {
            // 检查移除的节点是否包含高亮元素
            if (currentHighlightedElements.has(node)) {
              clearElementHighlight(node);
            }
            
            // 检查移除节点的子元素中是否有高亮元素
            const highlightedChildren = node.querySelectorAll && node.querySelectorAll('.browser-work-highlight');
            if (highlightedChildren) {
              highlightedChildren.forEach(child => {
                if (currentHighlightedElements.has(child)) {
                  clearElementHighlight(child);
                }
              });
            }
          }
        });
      }
    });
  });

  // 开始监听DOM变化
  if (document.body) {
    domObserver.observe(document.body, {
      childList: true,
      subtree: true
    });
  }

  // 初始化
  if (["complete", "interactive"].includes(document.readyState)) {
    initialize();
  } else {
    document.addEventListener("DOMContentLoaded", initialize);
    window.addEventListener("load", initialize);
  }
}
